<template>
  <!-- 卡口管理 -->
  <div class="bayonetinfo">
    <basic-container>
      <avue-crud
        class="bayonetinfo_crud"
        :option="option"
        :table-loading="loading"
        :data="data"
        :page.sync="page"
        :permission="permissionList"
        :before-open="beforeOpen"
        v-model="form"
        ref="crud"
        @row-update="rowUpdate"
        @row-save="rowSave"
        @row-del="rowDel"
        @search-change="searchChange"
        @search-reset="searchReset"
        @selection-change="selectionChange"
        @current-change="currentChange"
        @size-change="sizeChange"
        @refresh-change="refreshChange"
        @on-load="onLoad"
      >
        <!-- 左上方菜单内容 -->
        <template slot="menuLeft">
          <el-button
            type="danger"
            size="small"
            icon="el-icon-delete"
            plain
            v-if="permission.bayonetinfo_delete"
            @click="handleDelete"
          >
            删 除
          </el-button>
        </template>

        <!-- 地图表单自定义 -->
        <template slot="mapForm">
          <div v-if="showMap">
            <baidu-map class="map" :center="center" :zoom="zoom" @ready="handler">
              <el-input placeholder="关键词查询" v-model="searchWord" style="position:absolute;top:10px;left:10px;width:180px;">
                <template slot="append">
                  <el-button icon="el-icon-search" id="citySearch"></el-button>
                </template>
              </el-input>

              <bm-navigation anchor="BMAP_ANCHOR_TOP_RIGHT"></bm-navigation>
              <bm-marker :position="mapPosition" :dragging="dragging"></bm-marker>
            </baidu-map>
          </div>
        </template>

      </avue-crud>
    </basic-container>
  </div>
</template>

<script>
import {
  getList,
  getDetail,
  add,
  update,
  remove
} from "@/api/useronduty/bayonetinfo";
import { mapGetters } from "vuex";

export default {
  data() {
    return {
      form: {},
      query: {},
      data: [],
      loading: true,
      selectionList: [],
      page: {
        pageSize: this.$pageSize,
        currentPage: 1,
        total: 0
      },
      option: {
        calcHeight: 30,
        tip: false,
        searchShow: true,
        searchSpan: 5,
        searchMenuSpan: 4,
        border: true,
        viewBtn: true,
        selection: true,
        refreshBtn: true,
        columnBtn: false,
        dialogClickModal: false,
        column: [
          {
            label: "卡口名称",
            prop: "kkmc",
            align: "center",
            search: true,
            rules: [
              {
                required: true,
                message: "请输入卡口名称",
                trigger: "blur"
              }
            ]
          },
          {
            label: "卡口编号",
            prop: "kkbh",
            hide: true,
            rules: [
              {
                required: true,
                message: "请输入卡口编号",
                trigger: "blur"
              }
            ]
          },
          {
            label: "值班室人员",
            prop: "zbsry",
            align: "center",
            search: true,
            type: "select",
            dicUrl: "/api/riskPoint/riskmanagement/getInternalStaff",
            props: {
              label: "realName",
              value: "id"
            },
            rules: [
              {
                required: true,
                message: "请选择值班室人员",
                trigger: "change"
              }
            ]
          },
          {
            label: "值班室电话",
            prop: "zbsdh",
            align: "center",
            rules: [
              {
                required: true,
                message: "请输入值班室电话",
                trigger: "blur"
              }
            ]
          },
          {
            label: "允许停留时长(h)",
            prop: "yxtlsc",
            align: "center",
            type: "number",
            minRows: 0.5,
            maxRows: 24.0,
            step: 0.5,
            precision: 1
          },
          {
            label: "",
            prop: "map",
            span: 24,
            hide: true,
            formslot: true
          },
          {
            label: "经度",
            prop: "jd",
            align: "center",
            rules: [
              {
                required: true,
                message: "请输入经度",
                trigger: "blur"
              }
            ]
          },
          {
            label: "纬度",
            prop: "wd",
            align: "center",
            rules: [
              {
                required: true,
                message: "请输入纬度",
                trigger: "blur"
              }
            ]
          },
          {
            label: "备注",
            prop: "bz",
            align: "center",
            type: "textarea",
            span: 24,
            maxlength: 150
          }
        ]
      },
      // 地图
      mapPosition: {
        lng: 121.4472540000,
        lat: 31.3236200000
      },
      center: {
        lng: 121.4472540000,
        lat: 31.3236200000
      },
      zoom: 10,
      dragging: false,
      showMap: true,
      searchWord: ""
    };
  },
  computed: {
    ...mapGetters(["permission"]),

    // 卡口列表按钮权限
    permissionList() {
      return {
        addBtn: this.vaildData(this.permission.bayonetinfo_add, false),
        viewBtn: this.vaildData(this.permission.bayonetinfo_view, false),
        delBtn: this.vaildData(this.permission.bayonetinfo_delete, false),
        editBtn: this.vaildData(this.permission.bayonetinfo_edit, false)
      };
    },

    // 卡口列表勾选项ID
    ids() {
      let ids = [];
      this.selectionList.forEach(ele => {
        ids.push(ele.id);
      });
      return ids.join(",");
    }
  },
  watch: {

    // 表单经度
    'form.jd' (val) {
      if(val) {
        this.mapPosition.lng = val / 1
      }
    },
    
    // 表单纬度
    'form.wd' (val) {
      if(val) {
        this.mapPosition.lat = val / 1
      }
    }
    
  },
  methods: {
    // 地图处理事件
    handler({ BMap, map }) {
      let _this = this;
      map.addEventListener("click", function(e) {
        _this.form.jd = e.point.lng;
        _this.form.wd = e.point.lat;
      });

      _this.$nextTick(() => {
        document.getElementById("citySearch").addEventListener("click", function() {
          let localSearch = new BMap.LocalSearch(map);
          localSearch.setSearchCompleteCallback(searchResult => {
            let poi = searchResult.getPoi(0);
            if (!poi) {
              return _this.$message.warning("该地址不存在");
            } else {
              _this.center = {
                lng: poi.point.lng,
                lat: poi.point.lat
              };
              _this.form.jd = poi.point.lng;
              _this.form.wd = poi.point.lat;
            }
          });
          localSearch.search(_this.searchWord);
        });
      });
    },

    // 新增
    rowSave(row, done, loading) {
      add(row).then(
        () => {
          this.onLoad(this.page);
          this.$message.success("操作成功!");
          done();
        },
        error => {
          loading();
          window.console.log(error);
        }
      );
    },

    // 修改
    rowUpdate(row, index, done, loading) {
      update(row).then(
        () => {
          this.onLoad(this.page);
          this.$message.success("操作成功!");
          done();
        },
        error => {
          loading();
          console.log(error);
        }
      );
    },

    // 删除一条
    rowDel(row) {
      this.$confirm("确定将选择数据删除?", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          return remove(row.id);
        })
        .then(() => {
          this.onLoad(this.page);
          this.$message.success("操作成功!");
        });
    },

    // 删除多条
    handleDelete() {
      if (this.selectionList.length === 0) {
        this.$message.warning("请选择至少一条数据");
        return;
      }
      this.$confirm("确定将选择数据删除?", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          return remove(this.ids);
        })
        .then(() => {
          this.onLoad(this.page);
          this.$message.success("操作成功!");
          this.$refs.crud.toggleSelection();
        });
    },

    // 打开查看、新增、编辑弹窗前
    beforeOpen(done, type) {
      if (type === "add") {
        this.showMap = true;
        this.mapPosition = {
          lng: 121.4472540000,
          lat: 31.3236200000
        };
        this.center = {
          lng: 121.4472540000,
          lat: 31.3236200000
        };
      } else {
        getDetail(this.form.id).then(res => {
          this.form = res.data.data;
        });

        if (type === "edit") {
          this.showMap = true;
          this.center = {
            lng: this.form.jd,
            lat: this.form.wd
          };
          this.zoom = 10;
        } else if (type === "view") {
          this.showMap = false;
        }
      }
      done();
    },

    // 清空搜索条件
    searchReset() {
      this.query = {};
      this.onLoad(this.page);
    },

    // 搜索条件改变事件
    searchChange(params, done) {
      this.query = params;
      this.page.currentPage = 1;
      this.onLoad(this.page, params);
      done();
    },

    // 勾选
    selectionChange(list) {
      this.selectionList = list;
    },

    // 清空勾选
    selectionClear() {
      this.selectionList = [];
      this.$refs.crud.toggleSelection();
    },

    // 换页数
    currentChange(currentPage) {
      this.page.currentPage = currentPage;
      this.onLoad(this.page);
    },

    // 换每页显示数量
    sizeChange(pageSize) {
      this.page.pageSize = pageSize;
      this.onLoad(this.page);
    },

    // 刷新
    refreshChange() {
      this.onLoad(this.page, this.query);
    },

    // 获取表格数据
    onLoad(page, params = {}) {
      this.loading = true;
      getList(
        page.currentPage,
        page.pageSize,
        Object.assign(params, this.query)
      ).then(res => {
        const data = res.data.data;
        this.page.total = data.total;
        this.data = data.records;
        this.loading = false;
        this.selectionClear();
      });
    }
  }
};
</script>

<style lang="scss" scpoed>
.map {
  width: 100%;
  height: 500px;
}

.box {
  height: 100%;
}

.anchorBL {
  display: none;
}

.bayonetinfo {
  .avue-crud {
    .avue-crud__search {
      .avue-form__row:nth-child(1) {
        .el-form-item__label {
          text-align: unset;
        }
      }

      .avue-form__row:nth-child(2) {
        .el-form-item__label {
          width: 90px !important;
        }

        .el-form-item__content {
          margin-left: 90px !important;
        }
      }
    }
  }
}

.avue-dialog {
  .el-dialog {
    .avue-group {
      .avue-form__group {
        .el-form-item {
          .el-form-item__label {
            width: 120px !important;
          }

          .el-form-item__content {
            margin-left: 120px !important;
          }
        }
      }
    }
  }
}
</style>